package com.tqjc.utils;

import com.alibaba.fastjson.JSONObject;
import com.tqjc.common.BO.PLCWriteRequestParamBO;
import com.tqjc.common.BO.ResponseLabelDataBO;
import com.tqjc.system.common.constant.ConfigConstant;
import com.tqjc.system.common.constant.GlobalConstant;
import com.tqjc.system.common.constant.RemoteURLConstant;
import com.tqjc.system.core.util.SpringUtils;
import com.tqjc.system.system.util.SystemUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @description:
 * @Author: 86195
 * @Date: 2023/12/27 22:41
 **/
@Slf4j
public class PLCHttpsUtils {


    public static RestTemplate restTemplate;

    static {
        RestTemplate bean = SpringUtils.getBean(RestTemplate.class);
        restTemplate = bean;
    }


    public static void writeMoreVal(String url, PLCWriteRequestParamBO paramBO) {
        HttpHeaders headers = new HttpHeaders();
        Map<String, Object> body = new HashMap<>();
        body.put("mac_sn", paramBO.getMacSN());
        body.put("address", paramBO.getAddress());
        body.put("dataType", paramBO.getDataType());
        body.put("values", paramBO.getValue());
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Accept", "application/json");
        HttpEntity httpEntity = new HttpEntity<>(body, headers);
        restTemplate.postForObject(url, httpEntity, String.class);
    }




    public static <T> T sendPost(String url, Map body, Class<T> t) {
        T res = null;
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Accept", "application/json");
            HttpEntity httpEntity = new HttpEntity<>(body, headers);
            String resultPost = restTemplate.postForObject(url, httpEntity, String.class);
            res = JSONObject.parseObject(resultPost, t);
        } catch (Exception e){
            log.error("PLCHttpsUtils sendPost running error,接口调用异常",e);
            throw e;
        }
        return res;
    }


    public static <T> T sendGet(String url, Map body, Class<T> t){
        T res = null;
        try {
            String resultPost = restTemplate.getForObject(url, String.class,body);
            res = JSONObject.parseObject(resultPost, t);
        } catch (Exception e){
            log.error("PLCHttpsUtils sendPost running error,接口调用异常",e);
            throw e;
        }
        return res;

    }






    public static void write(String url, PLCWriteRequestParamBO paramBO) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        Map<String, Object> body = new HashMap<>();
        body.put("mac_sn", paramBO.getMacSN());
        body.put("address", paramBO.getAddress());
        body.put("dataType", paramBO.getDataType());
        body.put("values", paramBO.getValue());
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Accept", "application/json");
        HttpEntity httpEntity = new HttpEntity<>(body, headers);
        int i = 0;
        while (true){
            try {
                restTemplate.postForObject(url, httpEntity, String.class);
                Thread.sleep(800);
                //读值操作
                Map<String,String> paramMap = new HashMap(2);
                Map<String, String> snMap = SystemUtils.Sys_carInfo.get(ConfigConstant.CONFIG_TYPE_CAR_BAK_SN);
                String sn = snMap.get(paramBO.getMacSN());
                paramMap.put(GlobalConstant.STRING_LABEL,paramBO.getLabel());
                paramMap.put(GlobalConstant.STRING_SN,sn);
                ResponseLabelDataBO res = PLCHttpsUtils.sendPost(RemoteURLConstant.URL_READBC, paramMap, ResponseLabelDataBO.class);
                Map<String, String> content = res != null? res.getContent(): null;

                if(content != null){
                    String currentVal = content.get("currentVal") != null ?
                            content.get("currentVal").toLowerCase() : null;
                    if(Objects.equals(currentVal,paramBO.getValue())){
                        //标定完成后，跳出循环
                        break;
                    }
                }
                i++;
                if(i > 3){
                    throw new Exception("写值操作超过三次");
                }
                log.info("再次写值操作！！！");
            } catch (Exception e){
                log.error("PLCHttpsUtils write running error,接口调用异常",e);
                throw e;
            }

        }
    }


    public static boolean valIsSuccess(String sn,String label,String targetVal) throws IOException {
        Map<String,String> paramMap = new HashMap(2);
        paramMap.put(GlobalConstant.STRING_LABEL,label);
        paramMap.put(GlobalConstant.STRING_SN,sn);
        ResponseLabelDataBO res = PLCHttpsUtils.sendPost(RemoteURLConstant.URL_READBC, paramMap, ResponseLabelDataBO.class);
        Map<String, String> content = res != null? res.getContent(): null;
        if(content != null){
            String currentVal = content.get("currentVal") != null ?
                    content.get("currentVal").toLowerCase() : null;
            log.info("该标签label读取：{}，读取的值为：{}，目标值为：{}",label,currentVal,targetVal);
            if(Objects.equals(currentVal,targetVal)){
                return true;
            }
        }

        return false;

    }


}
